package com.letv.android.client.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;

import com.flurry.android.FlurryAgent;
import com.letv.android.client.broadcast.HomeKeyEventReceiver;
import com.letv.android.client.fragment.LetvBaseFragment;
import com.letv.android.client.fragment.LetvFragmentListener;
import com.letv.core.config.LetvConfig;
import com.letv.core.network.volley.Volley;
import com.letv.core.sysletvplayer.base.BaseActivity;
import com.letv.core.utils.ActivityUtils;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.StatisticsUtils;


/**
 * 所有activity的基类
 * 
 * @author zhuqiao
 *
 */
public abstract class LetvBaseActivity extends FragmentActivity {
    /**
     * 当页面是MainActivity或者第三方调起的页面且打开应用时（除了当前页面，其他页面都没有创建）, 描述是否上报了login、env
     */
    private static boolean isLoginStatatistics = false;

    protected Context mContext;
    /**
     * 当activity被系统回收时,是否保存fragment的状态
     */
    protected boolean mSaveFragmentWhenKilled = false;

    /**
     * activity管理器
     */
    private ActivityUtils mActivityUtils = ActivityUtils.getInstance();
    /**
     * home监听器（一个即可）
     */
    protected static HomeKeyEventReceiver mHomeKeyEventReceiver;

    protected boolean mKeepSingle = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

//        if (!LetvApplication.getInstance().hasInited()) {
//            LetvApplication.getInstance().init();
//        }
//        if (!LetvApplication.getInstance().isCdeStarting()) {
//            LetvApplication.getInstance().startCde();
//        }

        mContext = this;

        if (mKeepSingle)
            mActivityUtils.addActivity(getActivityName(), getActivity());
    }

    /**
     * 注册home键的监听
     */
    protected void registerHomeKeyEventReceiver() {
        try {
            mHomeKeyEventReceiver = new HomeKeyEventReceiver();
            IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            registerReceiver(mHomeKeyEventReceiver, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消home键的监听
     */
    protected void unRegisterHomeKeyEventReceiver() {
        try {
            unregisterReceiver(mHomeKeyEventReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public <T extends View> T getViewById(int id) {
        return (T) findViewById(id);
    }

    @SuppressWarnings("unchecked")
    protected <T extends View> T getViewById(View parent, int id) {
        return (T) parent.findViewById(id);
    }

    /**
     * 添加fragment
     * 
     * @param fragment
     */
    public void addFragment(Fragment fragment) {
        addFragments(fragment);
    }

    /**
     * 批量添加fragment
     * 
     * @param fragments
     */
    public void addFragments(Fragment... fragments) {
        if (fragments == null || fragments.length == 0) {
            return;
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        for (Fragment fragment : fragments) {
            if (!(fragment instanceof LetvFragmentListener)) {
                continue;
            }

            LetvFragmentListener listener = (LetvFragmentListener) fragment;

            String tag = listener.getTagName();
            if (TextUtils.isEmpty(tag)) {
                continue;
            }

            int fragmentRes = listener.getContainerId();
            if (fragmentRes <= 0) {
                continue;
            }

            if (fragmentManager.findFragmentByTag(tag) != null) {
                continue;
            }

            transaction.add(fragmentRes, fragment, tag);
        }

        try {
            // catch Activity has been destroyed error
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示fragment
     */
    public void showFragment(Fragment fragment) {
        showFragmentIfNeeded(fragment, false);
    }

    /**
     * 显示fragment.默认关闭其他activity
     * 
     * @param fragment
     */
    protected void showFragmentIfNeeded(Fragment fragment) {
        showFragmentIfNeeded(fragment, true);
    }

    /**
     * 显示fragment
     * 
     * @param fragment
     * @param hideOrRemoveOthers 是否关闭其他的fragment
     */
    public void showFragmentIfNeeded(Fragment fragment, boolean hideOrRemoveOthers) {
        if (!(fragment instanceof LetvFragmentListener)) {
            return;
        }

        LetvFragmentListener listener = (LetvFragmentListener) fragment;

        String tag = listener.getTagName();
        if (TextUtils.isEmpty(tag)) {
            return;
        }

        String[] tags = getAllFragmentTags();
        if (tags == null) {
            return;
        }

        int fragmentRes = listener.getContainerId();
        if (fragmentRes <= 0) {
            return;
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentByTag(tag) == null) {
            // 当没添加过该fragment时，添加
            transaction.add(fragmentRes, fragment, tag);
        }
        transaction.show(fragment);
        listener.onShow();

        if (hideOrRemoveOthers) {
            // 隐藏或移除其他fragment
            for (String hideTag : tags) {
                if (TextUtils.equals(tag, hideTag)) {
                    continue;
                }

                final Fragment fragmentNeedHide = fragmentManager.findFragmentByTag(hideTag);
                if (fragmentNeedHide instanceof LetvFragmentListener) {
                    int flag = ((LetvFragmentListener) fragmentNeedHide).getDisappearFlag();
                    if (flag == LetvBaseFragment.REMOVE) {
                        transaction.remove(fragmentNeedHide);
                    } else if (flag == LetvBaseFragment.HIDE) {
                        transaction.hide(fragmentNeedHide);
                        ((LetvFragmentListener) fragmentNeedHide).onHide();
                    } else {
                        // do nothing. keep
                    }
                }
            }
        }

        try {
            // catch Activity has been destroyed error
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除所有fragment
     */
    protected void deleteAllFragments() {
        String[] tags = getAllFragmentTags();
        if (tags == null) {
            return;
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        if (BaseTypeUtils.isListEmpty(fragmentManager.getFragments())) {
            return;
        }

        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (Fragment fragment : fragmentManager.getFragments()) {
            transaction.remove(fragment);
        }

        try {
            // catch Activity has been destroyed error
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏fragment
     * 
     * @param fragment
     */
    public void hideFragment(Fragment fragment) {
        if (fragment == null)
            return;

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.hide(fragment);

        if (fragment instanceof LetvBaseFragment) {
            ((LetvBaseFragment) fragment).onHide();
        }

        try {
            // catch Activity has been destroyed error
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏fragment
     * 
     * @param tag
     */
    public void hideFragment(String tag) {
        if (TextUtils.isEmpty(tag))
            return;

        FragmentManager fragmentManager = getSupportFragmentManager();
        hideFragment(fragmentManager.findFragmentByTag(tag));
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if (NetworkUtils.isNetworkAvailable() && FloatBallUtils.isGetFloatInfo()) {
//            requestFloatTaskThread();
//        }
        FlurryAgent.onStartSession(this, LetvConfig.getFlurryKey());
        // 从后台启动（home键点击后)
        if (mHomeKeyEventReceiver != null && mHomeKeyEventReceiver.isHomeClicked()) {
            isLoginStatatistics = false;
            LogInfo.LogStatistics("app start from home");
        }
    }

    /**
     * 删除fragment
     * 
     * @param fragment
     */
    public void removeFragment(Fragment fragment) {
        if (fragment == null)
            return;

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.remove(fragment);

        try {
            // catch Activity has been destroyed error
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        LetvApplication.getInstance().startShake(getActivityName());
        if (mHomeKeyEventReceiver != null) {
            mHomeKeyEventReceiver.setIsHomeClicked(false);
        }
        try {
            // 页面处于可见状态,打开应用
            if (LetvUtils.isAppOnForeground(mContext) && !isLoginStatatistics) {
                LogInfo.LogStatistics("app start");
                // 统计-login
                StatisticsUtils.statisticsLogin(mContext, 0);
                // 统计-env
                StatisticsUtils.statisticsEnv(mContext);
                isLoginStatatistics = true;
            }
        } catch (Exception e) {
            LogInfo.LogStatistics("main activity on resume exception:" + e.getMessage());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        LetvApplication.getInstance().stopShake();
//        ImageDownloader.getInstance(this).fluchCache();
        Volley.getInstance(mContext).flush();
    }

    @Override
    protected void onStop() {
        super.onStop();
        FlurryAgent.onEndSession(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        if (BaseTypeUtils.isListEmpty(fragmentManager.getFragments()) || mSaveFragmentWhenKilled) {
            super.onSaveInstanceState(outState);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mKeepSingle)
            mActivityUtils.removeActivity(getActivityName(), false);
        // 当前应用在后台了
        if (!LetvUtils.isAppOnForeground(mContext) && isLoginStatatistics) {
            StatisticsUtils.statisticsLogin(mContext, 1);
            isLoginStatatistics = false;
        }
    }

    public boolean isKeepSingle() {
        return mKeepSingle;
    }

    /**
     * 返回activity中所有fragment对应的tag
     * 
     * @return
     */
    public abstract String[] getAllFragmentTags();

    /**
     * activity名称.使用return XXActivity.class.getName()
     * 
     * @return
     */
    public abstract String getActivityName();

    /**
     * activity对象.使用return this
     * 
     * @return
     */
    public abstract Activity getActivity();

    public void upToHome(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(getApplicationContext(), cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
}
